<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { deleteReserve, getReserveByUserId, submitReserve } from '~/api/house'
import { deleteReserveById } from '~/api/delete'

const userString = localStorage.getItem('userInfo') as string
const user = JSON.parse(userString)

const reserves = ref([])
const total = ref(0)
const screenHeight = ref(window.innerHeight)
const tableHeight = computed(() => {
  return `${screenHeight.value - 200}px`
})

window.onresize = () => {
  screenHeight.value = window.innerHeight
}
const multipleTableRef = ref()
const multipleSelection = ref([])

function countTotal(arr: any, keyName: any) {
  let $total = 0
  $total = arr.reduce((total: any, currentValue: any, currentIndex: any, arr: any) => {
    return currentValue[keyName] ? total + currentValue[keyName] : total
  }, 0)
  return $total
}

// 多选框事件（当选择项发生变化时会触发该事件）
function handleSelectionChange(val: any) {
  multipleSelection.value = val
  console.log(val)
  // 计算房间总价
  if (val.length !== 0)
    total.value = countTotal(val, 'totalPrice')
}

// 提交按钮事件
async function handleSubmitReserve() {
  // 获取勾选项的id
  const ids = multipleSelection.value.map(item => item.id)
  // 通过id批量删除
  submitReserve(ids).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: '订单支付成功！',
        type: 'success',
      })
      // 刷新表格数据
      refreshTableData()
    }
  })
}

// 删除订单按钮事件
async function handleDeleteReserve() {
  const ids = multipleSelection.value.map(item => item.id)
  deleteReserve(ids).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: '订单删除成功！',
        type: 'success',
      })
      refreshTableData()
    }
  })
}

async function refreshTableData() {
  await getReserveByUserId(user.id).then((res: any) => {
    reserves.value = res.result
  })
}
refreshTableData()

function handlePay(scope: any) {
  const row = scope.row

  console.log(scope.row)
  // 跳转到支付页面
  window.open(`http://localhost:7777/alipay/pay?traceNo=${row.id}&totalAmount=${row.totalPrice}&subject=${user.id}_${row.houseId}`)
}

async function handleDelete(scope: any) {
  const row = scope.row
  await deleteReserveById(row.id).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: '删除成功！',
        type: 'success',
      })
      refreshTableData()
    }
  })
}
</script>

<template>
  <div class="main">
    <el-table
      ref="multipleTableRef"
      :data="reserves"
      style="width: 100%; margin: 20px"
      :height="tableHeight"
      :default-sort="{ prop: 'date', order: 'descending' }"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed="left" type="selection" width="55" />
      <el-table-column property="title" label="民宿" width="120" />
      <el-table-column property="img" label="图片" width="120">
        <template #default="scope">
          <el-image
            style="width: 120px; height: 80px"
            :src="scope.row.img"
          />
        </template>
      </el-table-column>

      <el-table-column property="startTime" label="入住时间" width="120" />
      <el-table-column property="endTime" label="退房时间" width="120" />
      <el-table-column property="createTime" label="预定时间" width="120" />

      <el-table-column property="price" label="价格" width="120" />
      <el-table-column property="days" label="入住天数" width="120" />
      <el-table-column property="totalPrice" label="小计" width="120" />
      <el-table-column prop="address" label="地址" width="120" />

      <el-table-column
        property="isPay" label="是否支付" width="120"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.isPay === 0" type="danger">
            未支付
          </el-tag>
          <el-tag v-else>
            已支付
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handlePay(scope)">
            支付
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="m-2" justify="end">
      房间总价：<span class="font-bold">{{ total }}</span>
    </el-row>
    <el-row class="m-2" justify="end">
      <el-button type="danger" plain @click="handleDeleteReserve()">
        删除订单
      </el-button>
      <el-button type="primary" class="bg-red-600" @click="handleSubmitReserve()">
        提交订单
      </el-button>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.main {
  width: 1000px;
}
</style>

<route lang="yaml">
  meta:
    layout: profile
  </route>
